import axios from "axios"
export default {
    namespaced: true,
    state: () => ({
        cart: []
    }),
    mutations:{
        updateCartList (state, cart) {
            state.cart = cart
        },
        // 单选状态
        updataOnState(state,payload){
            // {id: 1, value: false}
            let index = state.cart.findIndex(item => item.id === payload.id)
            state.cart[index].goods_state = payload.value
        },
        // 全选控制小选
        updataAllChecked(state,payload){
            return state.cart.forEach(item => item.goods_state = payload)
        },
        // 数量变化
        updataCount(state,payload){
            let index = state.cart.findIndex(item => item.id === payload.id)
            state.cart[index].goods_count = payload.value
        }
    }
    ,
    actions: {
        async getCartList (context) {
            const res = await axios.get('https://www.escook.cn/api/cart')
            console.log(res);
            context.commit('updateCartList', res.data.list)
        }
    },
    getters:{
        allPrice(state){
            return state.cart.filter(item => item.goods_state).reduce((sum, item) => sum += item.goods_count * item.goods_price, 0)
        },
        allCount(state){
            return state.cart.filter(item => item.goods_state).reduce((sum, item) => sum += item.goods_count, 0)
        }
    }
}